<?php

define('RR_API_SERVER', 'http://api.renren.com/restserver.do?');

define('RR_CONNECT_API_KEY', 'f8fd0175eca34eaabb7f6e377ad4283e');
define('RR_CONNECT_SECRET', '586c830b163149db890af7910ae542e6');
define('RR_CONNECT_UCENTER', $avatar_uc_path);
define('RR_CONNECT_TABLEPRE', $tablepre);

function mkdirs($dir)  
{  if(!is_dir($dir))  
{  if(!mkdirs(dirname($dir))){  return false;  }  
if(!mkdir($dir,0777)){  return false;  }  
}  return true;  
};
function get_avatar($uid, $size = 'middle', $type = '') {
	$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
	$uid = abs(intval($uid));
	$uid = sprintf("%09d", $uid);
	$dir1 = substr($uid, 0, 3);
	$dir2 = substr($uid, 3, 2);
	$dir3 = substr($uid, 5, 2);
	$typeadd = $type == 'real' ? '_real' : '';
	$relative = $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).$typeadd."_avatar_$size.jpg";
	if(!file_exists(DISCUZ_ROOT.RR_CONNECT_UCENTER."/data/avatar/".$dir1.'/'.$dir2.'/'.$dir3))
		{mkdirs(DISCUZ_ROOT.RR_CONNECT_UCENTER."/data/avatar/".$dir1.'/'.$dir2.'/'.$dir3);}
	return DISCUZ_ROOT.RR_CONNECT_UCENTER.'/data/avatar/'.$relative;
}

function upload_avatar($uid, $url, $size) {
	$save_path = get_avatar($uid, $size);
	
    $avatar_stream = fopen($url, "rb");
    if( $avatar_stream ) {
        $avatar_file = fopen( $save_path, "wb");
        if( $avatar_file ) 
		{
			if(file_exists($save_path))
			{
				while( !feof($avatar_stream) ){
					fwrite($avatar_file, fread($avatar_stream, 1024*8), 1024*8);
				}
			}
		}
    }
	if( $avatar_stream ){
		fclose($avatar_stream);
	}
	if( $avatar_file ){
		fclose($avatar_file);
	}
    return $save_path;
}

function rr_generate_sig($params, $secret=RR_CONNECT_SECRET) {
	ksort($params);
	$sig = '';
	foreach($params as $key=>$value) {
		$sig .= "$key=$value";
	}
	
	$sig .= $secret;
	
	return md5($sig);
}

function rr_get_session() {
	$connect_session = array (
									"user" => $_COOKIE[RR_CONNECT_API_KEY.'_user'],
									"session_key" => $_COOKIE[RR_CONNECT_API_KEY.'_session_key'],
									"ss" => $_COOKIE[RR_CONNECT_API_KEY.'_ss'],
									"expires" => $_COOKIE[RR_CONNECT_API_KEY.'_expires'],
									);

	return $connect_session;
}


function rr_verify() {
	$session = rr_get_session();
	
	if(empty($session) || empty($session['expires']) || time() > intval($session['expires']) ) 
		return false;
	else 
		return rr_generate_sig($session) == $_COOKIE[RR_CONNECT_API_KEY];
}

function rr_get_id() {
	return $_COOKIE[RR_CONNECT_API_KEY.'_user'];
}

function rr_get_session_key() {
	return $_COOKIE[RR_CONNECT_API_KEY.'_session_key'];
}

//返回dz的本地帐号，如果没有的话，注册一个临时的帐号；
//如果绑定了本地帐号，使用绑定过的;否则，使用临时的帐号
function rr_get_bind_id($db) {
	$rr_uid = rr_get_id();
	$tableRenRen=RR_CONNECT_TABLEPRE."renren_discuz";
	$query = "SELECT CASE tag WHEN '1' THEN dzuid WHEN '0' THEN defdzuid END AS dz_uid FROM $tableRenRen WHERE xnuid = '$rr_uid' ";
	if($result = $db->fetch_first($query))
		$discuz_uid = $result['dz_uid'];
	else
		$discuz_uid = rr_register($db, $rr_uid);
	
	return $discuz_uid;
}

function rr_get_bind_rr_id($db, $dz_uid) {
	$tableRenRen=RR_CONNECT_TABLEPRE."renren_discuz";
	$query = "SELECT xnuid FROM $tableRenRen WHERE defdzuid=$dz_uid OR dzuid=$dz_uid";
	$result = $db->fetch_first($query);
	return $result['xnuid'];
}
function rr_bind($db, $dz_uid, $rr_uid, $tag) {
	$tableRenRen=RR_CONNECT_TABLEPRE."renren_discuz";
	if($dz_uid!=1)
	{
	if($tag==0) 
		$db->query( "INSERT INTO $tableRenRen (defdzuid, xnuid, tag) VALUES ($dz_uid, $rr_uid, $tag)");
	else
		$db->query( "INSERT INTO $tableRenRen (dzuid, xnuid, tag) VALUES ($dz_uid, $rr_uid, $tag) ON DUPLICATE KEY UPDATE dzuid=$dz_uid and tag = $tag");
	}
}

function rr_register($db, $rr_uid) {
	define('NOROBOT', TRUE);
	require_once DISCUZ_ROOT.'./uc_client/client.php';
	
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}

	preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
	$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
	unset($onlineipmatches);
	
	$user_info = rr_get_user_info();
	$tinyurl_with_logo = $user_info->tinyurl_with_logo;	
	$headurl_with_logo = $user_info->headurl_with_logo;
	$username = $user_info->name;
	$password = md5(random(100));
	$email = "$rr_uid@renren.com";
	$questionid = '';
	$answer = '';
	
	$uid = uc_user_register($username, $password, $email, $questionid, $answer, $onlineip);
	if($uid <= 0) {
			if($uid == -1) {
				showmessage('profile_username_illegal');
			} elseif($uid == -2) {
				showmessage('profile_username_protect');
			} elseif($uid == -3) {
				$username = $user_info->name.$rr_uid;
				$uid = uc_user_register($username, $password, $email, $questionid, $answer, $onlineip);
				if($uid <= 0) {
						if($uid == -1) {
							showmessage('profile_username_illegal');
						} elseif($uid == -2) {
							showmessage('profile_username_protect');
						} elseif($uid == -3) {
							showmessage('profile_username_duplicate');
						} elseif($uid == -4) {
							showmessage('profile_email_illegal');
						} elseif($uid == -5) {
							showmessage('profile_email_domain_illegal');
						} elseif($uid == -6) {
							showmessage('profile_email_duplicate');
						} else {
							showmessage('undefined_action', NULL, 'HALTED');
						}
				}
			} elseif($uid == -4) {
				showmessage('profile_email_illegal');
			} elseif($uid == -5) {
				showmessage('profile_email_domain_illegal');
			} elseif($uid == -6) {
				showmessage('profile_email_duplicate');
			} else {
				showmessage('undefined_action', NULL, 'HALTED');
			}
	}
	 $tableMember=RR_CONNECT_TABLEPRE."members";
	 $tableMemberFields=RR_CONNECT_TABLEPRE."memberfields";
	if($db->result_first("SELECT uid FROM $tableMember WHERE uid='$uid'")) {
		uc_user_delete($uid);
		showmessage('profile_uid_duplicate');
	}
	if(!empty($headurl_with_logo)) {
		upload_avatar($uid,$headurl_with_logo,"middle");
	}
	if(!empty($tinyurl_with_logo)) {
		upload_avatar($uid,$tinyurl_with_logo,"small");
	}
	$birthday = $user_info->birthday;
	$sex = $user_info->sex;
	$location = $user_info->hometown_location->province.$user_info->hometown_location->city;
	$renren_profile = 'http://www.renren.com/profile.do?id='.$rr_uid;
	if(isset($sex)) {
		$sex = intval($sex) > 0 ? '1':'2';
	} else {
		$sex = '0';
	}

	$timestamp = time();
	$db->query("INSERT INTO $tableMember (uid, username, password, secques, adminid, groupid, regip, regdate, lastvisit, lastactivity, posts, credits,  email, bday, gender, showemail, timeoffset, pmsound, invisible, newsletter) VALUES ('$uid', '$username', '$password', '', '0', '10', '$onlineip', '$timestamp', '$timestamp', '$timestamp', '0', '0', '$email', '$birthday', '$sex', '0', '9999', '1', '0', '1')");
	$db->query("REPLACE INTO $tableMemberFields (uid, location,renren_profile) VALUES ('$uid', '$location', '$renren_profile')");
	global $bbname;
	$welcomtitle = iconv("utf-8", "gbk","欢迎使用人人连接登录$bbname!");
	$welcomemsgtxt = iconv("utf-8", "gbk","你好，").$username.iconv("utf-8", "gbk","!请继续完善资料");
	sendpm($uid, $welcomtitle, $welcomemsgtxt, 0);
	
	rr_bind($db, $uid, $rr_uid, 0);
	
	return $uid;
}

//------------下面是API接口调用的客户端----------------
function rr_get_user_info($uids=0) {
	if($uids)
	{
		$params = array("uids"=>$uids);
	}
	else
	{
		$params = array("fields"=> array('name','sex','star','birthday','tinyurl','headurl','tinyurl_with_logo','headurl_with_logo','mainurl','university_history','work_history','hs_history','hometown_location'),
			'v'=>'1.0'
		);
		

	}	
	//$params = array('page'=>0,'count'=>20);
	$user_info = rr_call_api('users.getInfo', $params);
	$result=$user_info[0];
	$bday=$result->birthday;
	if($bday)
	{
		if(strlen($bday)>=4)
		{
			if(substr($bday,0,2)==='17'){ 
				$result->birthday='0000'.substr($bday,4);
			}
		}
	}
	$username=$result->name;
	if($username)
	{
		$result->name=iconv("utf-8", "gbk",$username);
	}
	$city=$result->hometown_location->city;
	if($city)
	{
		$result->hometown_location->city=iconv("utf-8", "gbk",$city);
	}
	$province=$result->hometown_location->province;
	if($province)
	{
		$result->hometown_location->province=iconv("utf-8", "gbk",$province);
	}
	return $result;
}

function rr_call_api($method, $params) {
	$post_body = rr_post_body($method, $params);
	
	if (function_exists('curl_init')) {
		  $request = curl_init();
		  curl_setopt($request, CURLOPT_URL, RR_API_SERVER);
		  curl_setopt($request, CURLOPT_POST, 1);
		  curl_setopt($request, CURLOPT_POSTFIELDS, $post_body);
		  curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
		  
		  $result = curl_exec($request);
		  
		  curl_close($request);
	} else {
		$context =array('http' =>
					  array('method' => 'POST',
							'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n".
										'User-Agent: Facebook API PHP5 Client 1.1 '."\r\n".
										'Content-length: ' . strlen($post_body),
							'content' => $post_body));
			  $contextid=stream_context_create($context);
			  $sock=fopen(RR_API_SERVER, 'r', false, $contextid);
			  if ($sock) {
				$result='';
				while (!feof($sock))
				  $result.=fgets($sock, 4096);

				fclose($sock);
			  }
	}
	
	$result = rr_handle_response($result);
	
	return $result;
}

function rr_post_body($method, $params) {
	$params['format'] = $format;
	$params['method'] = $method;
if(!$params['uids'])
	{
	$params['session_key'] = rr_get_session_key();
	}
	$params['api_key'] = RR_CONNECT_API_KEY;
	$params['call_id'] = time();
	$params['format'] = 'JSON';
	
	if (!isset($params['v'])) {
		$params['v'] = '1.0';
	}
	
	$post_params = array();
	foreach ($params as $key => &$val) {
	  if (is_array($val)) $val = implode(',', $val);
	  $post_params[] = $key.'='.urlencode($val);
	}
	
	$post_params[] = 'sig='.rr_generate_sig($params);
	return implode('&', $post_params);
}

function rr_handle_response($result) {
	$array = json_decode($result);
	rr_check_response($array);
	
	return $array;
}

function rr_check_response($result) {
		$msg='';
		var_dump($result);
		if($result->error_code)
		{
			$msg.='<br>访问出错!<br>';
			if($result->error_code[0])
			{
				$msg.='错误编号:'.$result->error_code[0].'<br>';
			}
			if($result->error_msg)
			{
				$msg.='错误信息:'.$result->error_msg.'<br>';
			}
		}
		
		if($msg!='' && $result->error_code[0]!='10702' && $result->error_code[0]!='10600' ){
		$msg= iconv("utf-8", "gbk",$msg);
			echo $msg;
			exit;
		}
}


?>
